package com.farm.service.impl;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.farm.entity.User;
import com.farm.mapper.UserMapper;
import com.farm.service.UserService;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    @Transactional
    public void register(User user) {
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        // 设置初始状态（待审核）
        user.setStatus(0);
        // 设置初始余额
        user.setBalance(BigDecimal.ZERO);
        userMapper.insert(user);
    }

    @Override
    @Transactional
    public void updateUser(User user) {
        // 如果密码不为空，则加密
        if (user.getPassword() != null && !user.getPassword().trim().isEmpty()) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        userMapper.updateById(user);
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public User getCurrentUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated()) {
            return null;
        }
        String username = auth.getName();
        return userMapper.selectByUsername(username);
    }

    @Override
    @Transactional
    public void auditUser(Long userId, Integer status) {
        User user = new User();
        user.setId(userId);
        user.setStatus(status);
        userMapper.updateById(user);
    }

    @Override
    @Transactional
    public void recharge(Long userId, BigDecimal amount) {
        User user = userMapper.selectById(userId);
        if (user != null) {
            user.setBalance(user.getBalance().add(amount));
            userMapper.updateById(user);
        }
    }

    @Override
    @Transactional
    public boolean deductBalance(Long userId, BigDecimal amount) {
        User user = userMapper.selectById(userId);
        if (user != null && user.getBalance().compareTo(amount) >= 0) {
            user.setBalance(user.getBalance().subtract(amount));
            userMapper.updateById(user);
            return true;
        }
        return false;
    }
} 